package com.example.core.libs;

import lombok.Data;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.Map;

@Data
public class JSONResult {
    static private String DEFAULT_MESSAGE_SUCCESS = "success";
    static private String DEFAULT_MESSAGE_FAILED = "failed";

    private int code = 0;
    private Map<String, Object> data = new HashMap<>();
    private String message = DEFAULT_MESSAGE_SUCCESS;


    public JSONResult() {
    }

    public JSONResult(int code) {
        if (code != 0) {
            this.message = DEFAULT_MESSAGE_FAILED;
        }
        this.code = code;
    }

    public JSONResult(String message) {
        this.message = message;
    }

    public JSONResult(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public <T> JSONResult(Page<T> page, int currPage) {
        this.put("list", page.getContent())
                .put("total", page.getTotalElements())
                .put("totalPages", page.getTotalPages())
                .put("page", currPage);
    }

    public JSONResult(AppException e) {
        this.code = e.getCode();
        this.message = e.getMessage();
    }

    public JSONResult(SeckillStatEnum statEnum) {
        this.code = statEnum.getState();
        this.message = statEnum.getInfo();
    }

    public JSONResult(int code, String message, Map<String, Object> data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public JSONResult(BindingResult result) {
        Map<String, Object> errorMap = new HashMap<>();
        for (FieldError err : result.getFieldErrors()) {
            errorMap.put(err.getField(), err.getDefaultMessage());
        }

        this.code = 1111;
        this.message = "invalid params.";
        this.data = errorMap;
    }

    public Boolean getSuccess() {
        return code == 0;
    }

    public JSONResult put(String key, Object value) {
        data.put(key, value);
        return this;
    }

    public Object get(String key) {
        return data.get(key);
    }
}
